<template>
  <div class="app-container">
    <!-- <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="菜单名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><i-ep-search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><i-ep-refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div> -->

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="handleOpenDialog(0)">
          <template #icon><i-ep-plus /></template>
          新增
        </el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="menuTableData"
        highlight-current-row
        row-key="menuId"
        :expand-row-keys="['1']"
        @row-click="handleRowClick"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
      >
        <el-table-column label="菜单名称" min-width="200">
          <template #default="scope">
            <!-- <template
              v-if="scope.row.icon && scope.row.icon.startsWith('el-icon')"
            >
              <el-icon style="vertical-align: -0.15em">
                <component :is="scope.row.icon.replace('el-icon-', '')" />
              </el-icon>
            </template>
            <template v-else-if="scope.row.icon">
              <svg-icon :icon-class="scope.row.icon" />
            </template>
            <template v-else>
              <svg-icon icon-class="menu" />
            </template> -->
            {{ scope.row.menuName }}
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 'C'" type="warning">菜单</el-tag>
            <el-tag v-if="scope.row.type === 'A'" type="danger">
              公共按钮
            </el-tag>
            <el-tag v-if="scope.row.type === 'F'" type="info">普通按钮</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="路由路径"
          align="left"
          width="340"
          prop="menuUrl"
        />

        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.menuVisible === 0" type="success">
              显示
            </el-tag>
            <el-tag v-else type="info">隐藏</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="排序"
          align="center"
          width="80"
          prop="orderNum"
        />

        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click.stop="handleOpenDialog(scope.row.menuId)"
            >
              <i-ep-plus />
              新增
            </el-button>

            <el-button
              type="primary"
              link
              size="small"
              @click.stop="handleOpenDialog(undefined, scope.row.menuId)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click.stop="handleDelete(scope.row.menuId)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增 + 编辑表单 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      @close="handleCloseDialog"
      size="50%"
    >
      <el-form
        ref="menuFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级菜单"
            :data="menuOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="formData.menuName" placeholder="请输入菜单名称" />
        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio value="C">菜单</el-radio>
            <el-radio value="A">公共按钮</el-radio>
            <el-radio value="F">普通按钮</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.type == 'C'" prop="menuUrl">
          <template #label>
            <div>
              路由路径
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  定义应用中不同页面对应的 URL 路径，目录需以 /
                  开头，菜单项不用。例如：系统管理目录
                  /system，系统管理下的用户管理菜单 user。
                </template>
                <i-ep-QuestionFilled class="inline-block" />
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="formData.menuUrl" placeholder="user" />
        </el-form-item>

        <el-form-item prop="menuVisible" label="显示状态">
          <el-radio-group v-model="formData.menuVisible">
            <el-radio :value="0">显示</el-radio>
            <el-radio :value="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 权限标识 -->
        <!-- <el-form-item
          v-if="formData.type == "
          label="权限标识"
          prop="perm"
        >
          <el-input v-model="formData.perm" placeholder="sys:user:add" />
        </el-form-item> -->

        <!-- <el-form-item
          v-if="formData.type !== "
          label="图标"
          prop="icon"
        >
          图标选择器
          <icon-select v-model="formData.icon" />
        </el-form-item> -->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Menu",
  inheritAttrs: false,
});

import menuAPI, { MenuQuery, MenuForm, MenuVO } from "@/api/menu";

const queryFormRef = ref(ElForm);
const menuFormRef = ref(ElForm);

const loading = ref(false);
const dialog = reactive({
  title: "新增菜单",
  visible: false,
});

// 查询参数
const queryParams = reactive<MenuQuery>({
  keywords: "",
});
// 菜单表格数据
const menuTableData = ref<MenuVO[]>([]);
// 顶级菜单下拉选项
const menuOptions = ref<OptionType[]>([]);

// 初始菜单表单数据
const initialMenuFormData = ref<MenuForm>({
  menuId: undefined,
  parentId: undefined,
  menuName: "",
  orderNum: 0,
  menuUrl: "",
  menuVisible: 0,
  createBy: "",
  updateBy: "",
  type: "",
});

// 菜单表单数据
const formData = ref({ ...initialMenuFormData.value });

// 表单验证规则
const rules = reactive({
  parentId: [{ required: true, message: "请选择顶级菜单", trigger: "blur" }],
  menuName: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
  menuVisible: [{ required: true, message: "请选泽状态", trigger: "blur" }],
  menuUrl: [{ required: true, message: "请输入路径", trigger: "blur" }],
});

// 选择表格的行菜单ID
const selectedMenuId = ref<number | undefined>();

// 查询菜单
function handleQuery() {
  loading.value = true;
  menuAPI
    .getMenu()
    .then((data) => {
      console.log(data, "菜单列表");
      menuTableData.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  // queryFormRef.value.resetFields();
  handleQuery();
}

// 行点击事件
function handleRowClick(row: MenuVO) {
  // 记录表格选择的菜单ID，新增子菜单作为父菜单ID
  selectedMenuId.value = row.menuId;
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父菜单ID
 * @param menuId 菜单ID
 */
function handleOpenDialog(parentId?: number, menuId?: number) {
  console.log(parentId, menuId, "菜单参数");
  menuAPI.getMenu().then((data) => {
    let menus = sortMenusByOrderNum(data);
    menuOptions.value = [
      {
        value: 0,
        label: "顶级菜单",
        children: buildNestedMenuOptions(
          menus.filter((menu: { type: string }) => menu.type === "C")
        ),
      },
    ];
    dialog.visible = true;
    if (menuId) {
      dialog.title = "编辑菜单";
      menuAPI.getMenuQuery(menuId).then((data) => {
        console.log(data, "data");
        initialMenuFormData.value = { ...data };
        formData.value = data;
      });
    } else {
      dialog.title = "新增菜单";
      formData.value.parentId = parentId;
    }
  });
}
function sortMenusByOrderNum(menus: any) {
  return menus
    .sort(
      (a: { orderNum: number }, b: { orderNum: number }) =>
        a.orderNum - b.orderNum
    )
    .map((menu: { children: any[] }) => {
      if (menu.children && menu.children.length) {
        menu.children = sortMenusByOrderNum(menu.children);
      }
      return menu;
    });
}
function buildNestedMenuOptions(menus: any) {
  console.log(menus, "menus参数");
  return menus
    .map((menu: any) => {
      // 过滤掉 type 为 F 或 A 的菜单
      if (menu.type === "F" || menu.type === "A") {
        return null;
      }

      const option = {
        label: menu.menuName,
        value: menu.menuId,
        children: menu.children ? buildNestedMenuOptions(menu.children) : null,
      };

      // 如果当前菜单没有 children 或者 children 被过滤为空，则删除 children 属性
      if (!option.children || option.children.every((child: any) => !child)) {
        delete option.children;
      }

      return option;
    })
    .filter((option: null) => option !== null);
}

/** 菜单保存提交 */
function submitForm() {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formData.value.menuId;
      menuAPI.updateMenu(formData.value).then(() => {
        if (menuId) {
          ElMessage.success("修改成功");
        } else {
          ElMessage.success("新增成功");
        }
        handleCloseDialog();
        handleQuery();
      });
    }
  });
}

// 删除菜单
function handleDelete(menuId: number) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      menuAPI
        .deleteMenu(menuId)
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => {
          loading.value = false;
        });
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();
  // formData.value.menuId = undefined;
  // formData.value.menuUrl = "";
  formData.value = initialMenuFormData.value;
}

onMounted(() => {
  handleQuery();
});
</script>
